<html lang="en-US">

<head>
    
<title>「连载四」gRPC&#43;gRPC Gateway 能不能不用证书？ - 花落雨忧</title>

<meta property="og:title" content="「连载四」gRPC&#43;gRPC Gateway 能不能不用证书？ - 花落雨忧">



    



    
    <meta property="description" content="如果你以前有涉猎过 gRPC&#43;gRPC Gateway 这两个组件，你肯定会遇到这个问题，就是 “为什么非得开 TLS，才能够实现同端口双流量，能不能不开？” 又或是 “我不想用证书就实现这些功能，行不行？”。我被无数的人问过无数次这些问题，也说服过很多人，但说服归说服，不代表放弃。前年不行，不代表今年不行，在今天我希望分享来龙去脉和具体的实现方式给你。
[&amp;hellip;] &amp;hellip;">
    <meta property="og:description" content="如果你以前有涉猎过 gRPC&#43;gRPC Gateway 这两个组件，你肯定会遇到这个问题，就是 “为什么非得开 TLS，才能够实现同端口双流量，能不能不开？” 又或是 “我不想用证书就实现这些功能，行不行？”。我被无数的人问过无数次这些问题，也说服过很多人，但说服归说服，不代表放弃。前年不行，不代表今年不行，在今天我希望分享来龙去脉和具体的实现方式给你。
[&amp;hellip;] &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/grpc-gateway/2019-06-22-grpc-gateway-tls/">「连载四」gRPC&#43;gRPC Gateway 能不能不用证书？</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2019/06/22</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>如果你以前有涉猎过 gRPC+gRPC Gateway 这两个组件，你肯定会遇到这个问题，就是 <strong>“为什么非得开 TLS，才能够实现同端口双流量，能不能不开？”</strong> 又或是 <strong>“我不想用证书就实现这些功能，行不行？”</strong>。我被无数的人问过无数次这些问题，也说服过很多人，但说服归说服，不代表放弃。前年不行，不代表今年不行，在今天我希望分享来龙去脉和具体的实现方式给你。</p>
<p><img src="https://s2.ax1x.com/2020/02/27/3dLBAx.png" alt="image"></p>
<h2 id="过去">过去</h2>
<h3 id="为什么-h2-不行">为什么 h2 不行</h3>
<p>因为 <code>net/http2</code> 仅支持 &ldquo;h2&rdquo; 标识，而 &ldquo;h2&rdquo; 标识 HTTP/2 必须使用传输层安全性（TLS）的协议，此标识符用于 TLS 应用层协议协商字段以及识别 HTTP/2 over TLS。</p>
<p>简单来讲，也就 <code>net/http2</code> 必须使用 TLS 来交互。通俗来讲就要用证书，那么理所当然，也就无法支持非 TLS 的情况了。</p>
<h3 id="寻找-h2c">寻找 h2c</h3>
<p>那这条路不行，我们再想想别的路？那就是 HTTP/2 规范中的 &ldquo;h2c&rdquo; 标识了，&ldquo;h2c&rdquo; 标识允许通过明文 TCP 运行 HTTP/2 的协议，此标识符用于 HTTP/1.1 升级标头字段以及标识 HTTP/2 over TCP。</p>
<p>但是这条路，早在 2015 年就已经有在 <a href="https://github.com/golang/go/issues/13128#issuecomment-153193762">issue</a> 中进行讨论，当时 @bradfitz 明确表示 “不打算支持 h2c，对仅支持 TLS 的情况非常满意，一年后再问我一次”，原文回复如下：</p>
<blockquote>
<p>We do not plan to support h2c. I don&rsquo;t want to receive bug reports from users who get bitten by transparent proxies messing with h2c. Also, until there&rsquo;s widespread browser support, it&rsquo;s not interesting. I am also not interested in being the chicken or the egg to get browser support going. I&rsquo;m very happy with the TLS-only situation, and things like <a href="https://LetsEncrypt.org/">https://LetsEncrypt.org/</a> will make TLS much easier (and automatic) soon.</p>
</blockquote>
<blockquote>
<p>Ask me again in one year.</p>
</blockquote>
<h3 id="琢磨其他方式">琢磨其他方式</h3>
<h4 id="使用-cmux">使用 cmux</h4>
<p>基于多路复用器 <a href="https://github.com/soheilhy/cmux">soheilhy/cmux</a> 的另类实现 <a href="https://github.com/Stoakes/grpc-gateway-example">Stoakes/grpc-gateway-example</a>。若对 <code>cmux</code> 的实现方式感兴趣，还可以看看 <a href="https://blog.dgraph.io/post/cmux/">《Golang: Run multiple services on one port》</a>。</p>
<h4 id="使用第三方-h2">使用第三方 h2</h4>
<ul>
<li><a href="https://github.com/veqryn/h2c">veqryn/h2c</a></li>
</ul>
<p>这种属于自己实现了 h2c 的逻辑，以此达到效果。</p>
<h2 id="现在">现在</h2>
<p>经过社区的不断讨论，最后在 2018 年 6 月，代表 &ldquo;h2c&rdquo; 标志的 <code>golang.org/x/net/http2/h2c</code> 标准库正式合并进来，自此我们就可以使用官方标准库（h2c），这个标准库实现了 HTTP/2 的未加密模式，因此我们就可以利用该标准库在同个端口上既提供 HTTP/1.1 又提供 HTTP/2 的功能了。</p>
<h3 id="使用标准库-h2c">使用标准库 h2c</h3>
<pre tabindex="0"><code>import (
	...

	&#34;golang.org/x/net/http2&#34;
	&#34;golang.org/x/net/http2/h2c&#34;
	&#34;google.golang.org/grpc&#34;

	&#34;github.com/grpc-ecosystem/grpc-gateway/runtime&#34;

	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;
)

...

func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
	return h2c.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.ProtoMajor == 2 &amp;&amp; strings.Contains(r.Header.Get(&#34;Content-Type&#34;), &#34;application/grpc&#34;) {
			grpcServer.ServeHTTP(w, r)
		} else {
			otherHandler.ServeHTTP(w, r)
		}
	}), &amp;http2.Server{})
}

func main() {
	server := grpc.NewServer()

	pb.RegisterSearchServiceServer(server, &amp;SearchService{})

	mux := http.NewServeMux()
	gwmux := runtime.NewServeMux()
	dopts := []grpc.DialOption{grpc.WithInsecure()}

	err := pb.RegisterSearchServiceHandlerFromEndpoint(context.Background(), gwmux, &#34;localhost:&#34;+PORT, dopts)
	...
	mux.Handle(&#34;/&#34;, gwmux)
	http.ListenAndServe(&#34;:&#34;+PORT, grpcHandlerFunc(server, mux))
}
</code></pre><p>我们可以看到关键之处在于调用了 <code>h2c.NewHandler</code> 方法进行了特殊处理，<code>h2c.NewHandler</code> 会返回一个 <code>http.handler</code>，主要的内部逻辑是拦截了所有 <code>h2c</code> 流量，然后根据不同的请求流量类型将其劫持并重定向到相应的 <code>Hander</code> 中去处理。</p>
<h3 id="验证">验证</h3>
<h4 id="http11">HTTP/1.1</h4>
<pre tabindex="0"><code>$ curl -X GET &#39;http://127.0.0.1:9005/search?request=EDDYCJY&#39;
{&#34;response&#34;:&#34;EDDYCJY&#34;}
</code></pre><h4 id="http2grpc">HTTP/2(gRPC)</h4>
<pre tabindex="0"><code>...
func main() {
	conn, err := grpc.Dial(&#34;:&#34;+PORT, grpc.WithInsecure())
	...
	client := pb.NewSearchServiceClient(conn)
	resp, err := client.Search(context.Background(), &amp;pb.SearchRequest{
		Request: &#34;gRPC&#34;,
	})
}
</code></pre><p>输出结果：</p>
<pre tabindex="0"><code>$ go run main.go
2019/06/21 20:04:09 resp: gRPC h2c Server
</code></pre><h2 id="总结">总结</h2>
<p>在本文中我介绍了大致的前因后果，且介绍了几种解决方法，我建议你选择官方的 <code>h2c</code> 标准库去实现这个功能，也简单。在最后，不管你是否曾经为这个问题烦恼过许久，又或者正在纠结，都希望这篇文章能够帮到你。</p>
<h2 id="参考">参考</h2>
<ul>
<li><a href="https://github.com/golang/go/issues/13128">https://github.com/golang/go/issues/13128</a></li>
<li><a href="https://github.com/golang/go/issues/14141">https://github.com/golang/go/issues/14141</a></li>
<li><a href="https://github.com/golang/net/commit/c4299a1a0d8524c11563db160fbf9bddbceadb21">https://github.com/golang/net/commit/c4299a1a0d8524c11563db160fbf9bddbceadb21</a></li>
<li><a href="https://go-review.googlesource.com/c/net/+/112997/">https://go-review.googlesource.com/c/net/+/112997/</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc-gateway/2018-03-04-swagger/">「连载三」Swagger了解一下</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc-gateway/2018-02-27-hello-world/">「连载二」Hello World</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc-gateway/2018-02-23-install/">「连载一」gRPC介绍与环境安装</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/talk/2019-06-16-defer-loss/">Go1.12 defer 会有性能损耗，尽量不要用？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/defer/2019-05-27-defer/">深入理解 Go defer</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc-gateway" title="View all posts tagged match">grpc-gateway</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/talk/2019-06-16-defer-loss/"
                                                    rel="prev">Go1.12 defer 会有性能损耗，尽量不要用？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/talk/2019-06-29-talking-grpc/">从实践到原理，带你参透 gRPC</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>